package com.power200.android.service;

import android.util.Log;

import com.power200.android.bean.BackLog;
import com.power200.android.enumeration.BacklogEnum;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liuming on 10/11/15.
 */
public class BackLogService {

    private FileService fileService = new FileService();

    private static int currentIndex = 0;

    private static final String DIR = "/mmg";
    private static final String META_INFO = "/mmg/master-life-bls.meta";
    private static final String Path = "/mmg/master-life-bls.dat";

    private BackLogService() {
    }

    private List<BackLog> backLogList = new ArrayList<BackLog>();
    private List<BackLog> availableBackLogList = new ArrayList<BackLog>();

    public void init() {
        // read from local file
    }

    public void createBackLog(BackLog backLog) {
        // write file
        backLogList.add(backLog);
        availableBackLogList.add(backLog);
        File file = fileService.openFile(getPath());
        try {
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file, true));
            osw.write(backLog.toFileString() + "\n");
            osw.flush();
            osw.close();
        } catch (FileNotFoundException e) {
            Log.e("File", "FileNotFoundException", e);
        } catch (IOException e) {
            Log.e("File", "IOException", e);
        }
    }

    public void refreshFile() {
        // write file
        currentIndex++;
        File file = fileService.openFile(getPath());
        try {
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file, true));
            for (BackLog backLog : backLogList) {
                osw.write(backLog.toFileString() + "\n");
            }
            osw.flush();
            osw.close();
        } catch (FileNotFoundException e) {
            Log.e("File", "FileNotFoundException", e);
        } catch (IOException e) {
            Log.e("File", "IOException", e);
        }
    }

    public List<BackLog> getBackLogs() {
        return backLogList;
    }

    public List<BackLog> getAvailableBackLogList() {
        return availableBackLogList;
    }

    public static BackLogService getInstance() {
        if (instance == null) {
            instance = new BackLogService();
            instance.initBacklogList();
        }
        return instance;
    }

    private void initBacklogList() {
        mkdir();
        loadCurrentIndex();
        backLogList.clear();
        availableBackLogList.clear();
        try {
            File file = fileService.openFile(getPath());
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file));
            BufferedReader bufferedReader = new BufferedReader(isr);
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                BackLog backlog = BackLog.parseToFileString(line);
                backLogList.add(backlog);
                if (backlog.getStatus() != BacklogEnum.COMPLETE.value()) {
                    availableBackLogList.add(backlog);
                }
            }
        } catch (FileNotFoundException e) {
            Log.e("File", "FileNotFoundException", e);
        } catch (IOException e) {
            Log.e("File", "IOException", e);
        }
        Log.i("File", "Init");
    }

    public void delete(BackLog backLog) {
        backLogList.remove(backLog);
        availableBackLogList.remove(backLog);
        refresh();
    }

    public void refresh() {
        refreshFile();
        refreshCurrentIndex();
        availableBackLogList.clear();
        for (BackLog each : backLogList) {
            if(each.getStatus() != BacklogEnum.COMPLETE.value()) {
                availableBackLogList.add(each);
            }
        }
    }

    private static BackLogService instance = null;


    public static String getPath() {
        return currentIndex == 0 ? Path : Path + currentIndex;
    }

    private void loadCurrentIndex() {
        try {
            File file = fileService.openFile(META_INFO);
            if (!file.exists()) {
                return;
            }
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file));
            BufferedReader bufferedReader = new BufferedReader(isr);
            String line = bufferedReader.readLine();

            currentIndex = Integer.parseInt(line);
        } catch (FileNotFoundException e) {
            Log.e("File", "FileNotFoundException", e);
        } catch (IOException e) {
            Log.e("File", "IOException", e);
        } catch (Exception e) {
            Log.e("File", "Failed to paseException", e);
        }
    }

    private void refreshCurrentIndex() {
        File file = fileService.openFile(META_INFO);
        try {
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file));
            osw.write("" + currentIndex);
            osw.flush();
            osw.close();
        } catch (FileNotFoundException e) {
            Log.e("File", "FileNotFoundException", e);
        } catch (IOException e) {
            Log.e("File", "IOException", e);
        } catch (Exception e) {
            Log.e("File", "Exception", e);
        }
    }

    private void mkdir() {
        File file = fileService.openFile(DIR);
        if (!file.exists()) {
            file.mkdir();
        }
    }
}
